package com.sgb.kjwl.view.ui.activity.manage;

import android.Manifest;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.androidkun.xtablayout.XTabLayout;
import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityManageBinding;
import com.sgb.kjwl.interfaces.RecyclerClick;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.TwoLevelChildForPopWindowEntity;
import com.sgb.kjwl.model.entity.TwoLevelForPopWindowEntity;
import com.sgb.kjwl.model.entity.enterprise.IpPickSelectEntity;
import com.sgb.kjwl.model.entity.manage.TheEnterpriseOfEntityForManageList;
import com.sgb.kjwl.utils.DialogFunction;
import com.sgb.kjwl.utils.DialogHelper;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.ui.activity.self.authentication.AuthActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.adapter.manage.ManageEnterprisesAdapter;
import com.sgb.kjwl.view.widget.ActionBar;
import com.sgb.kjwl.view.widget.EnterprisePopWindow;
import com.sgb.kjwl.view.widget.IpPopWindow;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.view.widget.TwoLevelEntityPopWindow;
import com.sgb.kjwl.viewmodel.manage.ManageListViewModel;
import com.swgk.core.helper.OnMultiClickListener;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ManageActivity extends AppActivity {

    ActivityManageBinding mBinding;
    ManageListViewModel mManageListModel;
    ManageEnterprisesAdapter mManageEnterprisesAdapter;
    private boolean mIsLoadMore,mIsSpecialTypeChange;
    private int mPage;
    private List<PickSelectEntity<List<PickSelectEntity>>> mManage = new ArrayList<>();
    private String name,mIndustryTypeName = "",mOneLevelNo = "",mTwoLevelNo = "",mAreaCode = "",mCityNos = "",mCityName = "",mQualificationClassNo = "",mHonorTypeName = "",mHonorType = "",mDictId = "";
    String longitude,latitude;
    private TwoLevelEntityPopWindow<TwoLevelForPopWindowEntity> mTypePopWindow;
    private ThreeLevelAreaWindow mTheEnterpriseOfAreaPopWindow;
    private EnterprisePopWindow mSpecialTypeWindow,mHonorTypeWindow;
    private IpPopWindow homeGoodsSelectionTypePopWindow;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActionBar.setMenuFunctionClick(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                name = mActionBar.getEditText();
                loadData(false);
            }
        });

        mActionBar.setClearEdiText(new ActionBar.ClearEdiText() {
            @Override
            public void clearEdiText() {
                name = "";
                loadData(false);
            }

            @Override
            public void search() {
                closeKeybord();
                loadData(false);
            }
        });
        initData();
        initSelect();
        initRecyclerView();
        initLiveData();
        initButton();
        initTabLayout();
        initPermission();
    }

    private void initPermission() {
        if (PermissionsUtil.hasPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) && PermissionsUtil.hasPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
            return;
        } else {
            PermissionsUtil.requestPermission(this, new PermissionListener() {
                @Override
                public void permissionGranted(@NonNull String[] permissions) {
                    AuthActivity.start(getActivity());
                }

                @Override
                public void permissionDenied(@NonNull String[] permissions) {
                    Toast.makeText(ManageActivity.this, "定位失败，请开启定位后重试！", Toast.LENGTH_LONG).show();
                }
            }, Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION);
        }
    }

    @Override
    protected void initView() {
        super.initView();
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_manage);
        mBinding.setLifecycleOwner(this);
        mManageListModel = new ViewModelProvider(this).get(ManageListViewModel.class);

        longitude = getIntent().getStringExtra("longitude");
        latitude = getIntent().getStringExtra("latitude");
    }

    private void initButton(){
        mBinding.tvType.setOnClickListener(this);
        mBinding.tvArea.setOnClickListener(this);
        mBinding.tvIntelligenceType.setOnClickListener(this);
        mBinding.tvHonorType.setOnClickListener(this);
        mBinding.editView.setOnClickListener(this);
    }

    private void initTabLayout(){
        mBinding.tabLayout.addOnTabSelectedListener(new XTabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(XTabLayout.Tab tab) {
                mDictId = mManage.get(tab.getPosition()).getNo();
                loadData(false);
            }

            @Override
            public void onTabUnselected(XTabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(XTabLayout.Tab tab) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.tv_type:
                showType();
                mBinding.tvType.contentSelect(false,true);
                break;
            case R.id.tv_area:
                showCity();
                mBinding.tvArea.contentSelect(false,true);
                break;
            case R.id.tv_intelligence_type:
                showSpecial();
                mBinding.tvIntelligenceType.contentSelect(false,true);
                break;
            case R.id.tv_honor_type:
                showHonor();
                mBinding.tvHonorType.contentSelect(false,true);
                break;
            case R.id.edit_view:
                mBinding.editView.setImageResource(R.mipmap.btn_expand_up_gray);
                showManage();
                break;
        }
    }

    private void initRecyclerView(){
        mBinding.xrvManageList.setLayoutManager(new LinearLayoutManager(this));
        mManageEnterprisesAdapter = new ManageEnterprisesAdapter(this,null);
        mBinding.xrvManageList.setAdapter(mManageEnterprisesAdapter);
        mBinding.xrvManageList.setFootViewText("正在加载","没有更多啦");
        mManageEnterprisesAdapter.setOnItemClick(new AdapterOnItemClick<TheEnterpriseOfEntityForManageList>() {
            @Override
            public void onItemClick(TheEnterpriseOfEntityForManageList theEnterpriseOfEntity, int position) {
                if (!TextUtils.isEmpty(theEnterpriseOfEntity.getSupplier())){
                    WebsiteInfoActivity.start(getActivity(),theEnterpriseOfEntity.getSupplier(),1);
                }else {
                    Toast.makeText(getActivity(), "公司no为空", Toast.LENGTH_SHORT).show();
                }
            }
        });
        mManageEnterprisesAdapter.setmRecyclerClick(new RecyclerClick<TheEnterpriseOfEntityForManageList>() {
            @Override
            public void followClick(TheEnterpriseOfEntityForManageList entity) {
                if (DialogHelper.checkLogin()) {
                    if (entity.getFollow()) {
                        DialogHelper.showDialog(ManageActivity.this, "提示", "确定取消关注该企业？", "取消关注", new DialogFunction() {
                            @Override
                            public void normalRoundDialog() {
                                mManageListModel.follow(entity.getSupplier());
                            }
                        });
                    } else {
                        mManageListModel.follow(entity.getSupplier());
                    }
                } else {
                    VerificationCodeLoginActivity.start(ManageActivity.this, EventConstant.EVENT_MANAGE);
                }
            }
        });

        mBinding.xrvManageList.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData(false);
            }

            @Override
            public void onLoadMore() {
                loadData(true);
            }
        });
    }

    private void initLiveData(){
        mManageListModel.mEnterpriseList.observe(this, theEnterpriseOfEntities -> {
            mBinding.xrvManageList.refreshComplete();
            if (mIsLoadMore) {
                if (null != theEnterpriseOfEntities && theEnterpriseOfEntities.size() > 0) {
                    mBinding.xrvManageList.loadMoreComplete();
                    mManageEnterprisesAdapter.addDatas(theEnterpriseOfEntities);
                } else {
                    mBinding.xrvManageList.setNoMore(true);
                }
                mBinding.xrvManageList.setVisibility(View.VISIBLE);
            } else {
                mBinding.xrvManageList.refreshComplete();
                if (null != theEnterpriseOfEntities && theEnterpriseOfEntities.size() > 0) {
                    mBinding.xrvManageList.setVisibility(View.VISIBLE);
                    mBinding.emptyView.setVisibility(View.GONE);
                    mManageEnterprisesAdapter.setDatas(theEnterpriseOfEntities);
                    mBinding.xrvManageList.setLoadingMoreEnabled(true);
                } else {
                    mManageEnterprisesAdapter.setDatas(null);
                    mBinding.xrvManageList.setVisibility(View.GONE);
                    mBinding.emptyView.setVisibility(View.VISIBLE);
                }
            }
        });

        mManageListModel.mIndustryType.observe(this, twoLevelChildForPopWindowEntities -> mTypePopWindow.setData(twoLevelChildForPopWindowEntities));

        mManageListModel.mSuccessFollow.observe(this, aBoolean -> loadData(false));

        mManageListModel.mCityList.observe(this, addressEntities -> mTheEnterpriseOfAreaPopWindow.setDataForCompany(addressEntities, true));

        mManageListModel.mHonorType.observe(this, pickSelectEntities -> mHonorTypeWindow.setData(pickSelectEntities));

        mManageListModel.mSpecialType.observe(this, pickSelectEntities -> mSpecialTypeWindow.setData(pickSelectEntities));

        mManageListModel.mLoading.observe(this, aBoolean -> com.swgk.core.dialog.DialogHelper.showProgressDialog(this, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false));

        mManageListModel.mSuccess.observe(this, aBoolean -> com.swgk.core.dialog.DialogHelper.dismissProgressDialog());

        mManageListModel.mError.observe(this, aBoolean -> com.swgk.core.dialog.DialogHelper.dismissProgressDialog());

        mManageListModel.mManageType.observe(this, pickSelectEntities -> {
            mManage = pickSelectEntities;
            List<IpPickSelectEntity> dictData = new ArrayList<>();
            for (PickSelectEntity oneDatum : pickSelectEntities) {
                IpPickSelectEntity menuEntity = new IpPickSelectEntity(oneDatum.getNo(), oneDatum.getProjectscale(),"","","","","");
                dictData.add(menuEntity);
                mBinding.tabLayout.addTab(mBinding.tabLayout.newTab().setText(oneDatum.getProjectscale()));
            }
            homeGoodsSelectionTypePopWindow.setData(dictData);
        });
    }

    private void initData(){
        mManageListModel.getTradeTypes();
        mManageListModel.getCityData();
        mManageListModel.getHonorType();
        mManageListModel.findMyListByCompanyInfoNo();
        mManageListModel.getTypeList();
        loadData(false);
    }

    private void initSelect(){
        mTypePopWindow = new TwoLevelEntityPopWindow<>(getActivity());
        mTypePopWindow.setBgView(mBinding.grayLayout);
        mTypePopWindow.setmTwoLevelClick(new TwoLevelEntityPopWindow.TwoLevelClick<TwoLevelForPopWindowEntity>() {
            @Override
            public void oneClick(TwoLevelChildForPopWindowEntity<List<TwoLevelForPopWindowEntity>> d, int position) {
                mIndustryTypeName = d.getName();
                if (!mOneLevelNo.equals(d.getId())) {
                    mTwoLevelNo = "";
                }
                mOneLevelNo = d.getId();

            }

            @Override
            public void twoClick(TwoLevelForPopWindowEntity twoLevelEntityForPopWindow, int position) {
                mIndustryTypeName = twoLevelEntityForPopWindow.getName();
                mTwoLevelNo = twoLevelEntityForPopWindow.getId();
            }

            @Override
            public void reset() {
                mTypePopWindow.dismiss();
                loadData(false);
            }
        });

        mTypePopWindow.setOnResultClick((key1, key2, key3) -> loadData(false));
        mTypePopWindow.setOnDismissListener(() -> mBinding.tvType.contentSelect(!mIndustryTypeName.equals("不限") && !mIndustryTypeName.equals(""), false));

        // 省 城市
        mTheEnterpriseOfAreaPopWindow = new ThreeLevelAreaWindow(getActivity()) {
            @Override
            protected void provinceClick(BaseAreaEntity baseAreaEntity, int position) {
                super.provinceClick(baseAreaEntity, position);
                mCityName = baseAreaEntity.getSimpleName();
                if (!mAreaCode.equals(baseAreaEntity.getId())) {
                    mCityNos = "";

                }
                mAreaCode = baseAreaEntity.getId();
            }

            @Override
            protected void cityClick(BaseAreaEntity baseAreaEntity, int position) {
                super.cityClick(baseAreaEntity, position);
                mCityNos = baseAreaEntity.getId();

                mCityName = baseAreaEntity.getSimpleName();
            }

            @Override
            protected void reset() {
                super.reset();
                mTheEnterpriseOfAreaPopWindow.dismiss();
                loadData(false);
            }
        };
        mTheEnterpriseOfAreaPopWindow.setBgView(mBinding.grayLayout);
        mTheEnterpriseOfAreaPopWindow.setThreeListIsGone(true);
        mTheEnterpriseOfAreaPopWindow.setProvinceSingle();
        mTheEnterpriseOfAreaPopWindow.setCitySingle();
        mTheEnterpriseOfAreaPopWindow.setOnResultClick((key1, key2, key3) -> loadData(false));
        mTheEnterpriseOfAreaPopWindow.setOnDismissListener(() -> {
            mBinding.tvArea.contentSelect(!mCityName.equals("") && (!mCityName.equals("不限")), false);
            if (mAreaCode.equals("")) {
                mBinding.tvArea.contentSelect(false, false);
            }
        });

        mSpecialTypeWindow = new EnterprisePopWindow(getActivity());
        mSpecialTypeWindow.setBgView(mBinding.grayLayout);
        mSpecialTypeWindow.setOnResultClick((key1, key2, key3) -> {
            mQualificationClassNo = (String) key1;
            String name = (String) key2;
            if (!name.equals("不限")) {
                mIsSpecialTypeChange = true;
                mBinding.tvIntelligenceType.contentSelect(true,false);
            } else {
                mIsSpecialTypeChange = false;
                mBinding.tvIntelligenceType.contentSelect(false,false);
            }
            loadData(false);
        });
        mSpecialTypeWindow.setOnDisMissClick(() -> {
            if (!mIsSpecialTypeChange) {
                mBinding.tvIntelligenceType.contentSelect(false,false);
            }
        });
        // 距离
        mHonorTypeWindow = new EnterprisePopWindow(getActivity());
        mHonorTypeWindow.setBgView(mBinding.grayLayout);
        mHonorTypeWindow.setOnResultClick((key1, key2, key3) -> {
            mHonorTypeName = (String) key2;
            mHonorType = (String) key1;
            loadData(false);
        });
        mHonorTypeWindow.setOnDisMissClick(() -> mBinding.tvHonorType.contentSelect(!mHonorTypeName.equals("") && !mHonorTypeName.equals("不限"), false));

        homeGoodsSelectionTypePopWindow = new IpPopWindow(this);
        homeGoodsSelectionTypePopWindow.setDefItem(0);
        homeGoodsSelectionTypePopWindow.setBgView(mBinding.grayLayout);

        homeGoodsSelectionTypePopWindow.setOnResultClick((key1, key2, key3) -> {
            mBinding.tabLayout.getTabAt(((int) key2)).select();
            mBinding.editView.setImageResource(R.mipmap.btn_expand1);
        });
        homeGoodsSelectionTypePopWindow.setOnDismissListener(() -> mBinding.editView.setImageResource(R.mipmap.btn_expand1));
    }

    private void loadData(boolean isLoadMore){
        /**
         * category	number
         * 非必须
         * 行业分类二级code
         * registeredCapital	number
         * 非必须
         * 注册资金code
         * serviceType	number
         * 非必须
         * 行业分类code
         * staffNumber	integer
         * 非必须
         * 企业人数范围id（人数分类接口中的id）
         * follow	boolean
         * 必须
         * 是否关注
         */
        mPage = isLoadMore ? mPage + 1 : 1;
        mIsLoadMore = isLoadMore;
        Map<String,Object> map = new HashMap<>();
        map.put("industryCategory2", mTwoLevelNo);
        map.put("industryCategory1", mOneLevelNo);
        map.put("areaNo", mCityNos);
        map.put("provinceNo", mAreaCode);
        map.put("honorClassification", mHonorType);
        map.put("companyQualityNo", mQualificationClassNo);
        map.put("onMap", "0");
        map.put("limit", 20);
        map.put("page", mPage);
        map.put("name",name);
        map.put("distance", "");
        map.put("serviceType",mDictId);
        map.put("latitude",latitude);
        map.put("longitude",longitude);
        mManageListModel.getManageList(map);
    }

    private void showType() {
        mTypePopWindow.showPopwindow(mBinding.llTop, 0, 0);
    }

    private void showCity() {
        mTheEnterpriseOfAreaPopWindow.showPopwindow(mBinding.llTop, 0, 0);
    }

    private void showHonor(){
        mHonorTypeWindow.showPopwindow(mBinding.llTop, 0, 0);
    }

    private void showSpecial(){
        mSpecialTypeWindow.showPopwindow(mBinding.llTop, 0, 0);
    }

    private void showManage(){
        homeGoodsSelectionTypePopWindow.showPopwindow(mBinding.rlTop, 0,0);
    }
}
